#!/usr/bin/env python
import dieu.util, dieu.settings, dieu.database, dieu.bookmark
import pynotify
import webbrowser
import gtk
import gobject
import sys

class DieuAddPost:
    def __init__(self, Title='', URL='', Extra='', Tags=''):
        self.post_window = gtk.Window()
        self.post_window.set_title('Add bookmark')
        self.post_window.set_icon_from_file('@prefix@/share/pixmaps/dieu/bookmark-web.png')
        self.post_window.set_position(gtk.WIN_POS_CENTER)
        self.post_window.connect("delete_event", lambda w,e: self.cancel_action())
        self.post_window.set_border_width(12)
        self.post_window.set_resizable(False)
        self.post_window.set_keep_above(True)
        
        self.vbox = gtk.VBox(False, 0)
        self.post_window.add(self.vbox)
        
        self.uppertable = gtk.Table(2, 8)
        self.uppertable.set_row_spacings(6)
        self.vbox.pack_start(self.uppertable)
        
        self.labels_url = gtk.Label('_URL:')
        self.labels_url.set_alignment(1.0, 0.5)
        self.labels_url.set_use_underline(True)
        self.uppertable.attach(self.labels_url, 0, 1, 0, 1, gtk.FILL, xpadding=6)
        self.entries_url = gtk.Entry()
        self.uppertable.attach(self.entries_url, 1, 2, 0, 1)
        self.labels_url.set_mnemonic_widget(self.entries_url)
        
        self.labels_desc = gtk.Label('_Description:')
        self.labels_desc.set_alignment(1.0, 0.5)
        self.labels_desc.set_use_underline(True)
        self.uppertable.attach(self.labels_desc, 0, 1, 1, 2, gtk.FILL, xpadding=6)
        self.entries_desc = gtk.Entry()
        self.entries_desc.connect("changed", lambda w: self.post_window.set_title('Add "'+self.entries_desc.get_text()+'"'))
        self.uppertable.attach(self.entries_desc, 1, 2, 1, 2)
        self.labels_desc.set_mnemonic_widget(self.entries_desc)
        
        self.labels_notes = gtk.Label('_Notes:')
        self.labels_notes.set_alignment(1.0, 0.5)
        self.labels_notes.set_use_underline(True)
        self.uppertable.attach(self.labels_notes, 0, 1, 2, 3, gtk.FILL, xpadding=6)
        self.labels_notesremaining = gtk.Label('255 chars. left')
        self.uppertable.attach(self.labels_notesremaining, 0, 1, 3, 4, gtk.FILL, xpadding =6)
        self.labels_notesremaining.set_alignment(1.0, 0.5)
        self.labels_notesremaining.set_sensitive(False)
        self.scrolledwindow = gtk.ScrolledWindow()
        self.scrolledwindow.set_shadow_type(gtk.SHADOW_IN)
        self.scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        self.entries_notes_textbuffer = gtk.TextBuffer()
        self.entries_notes = gtk.TextView(self.entries_notes_textbuffer)
        self.entries_notes.set_wrap_mode(gtk.WRAP_WORD)
        self.scrolledwindow.add(self.entries_notes)
        self.uppertable.attach(self.scrolledwindow, 1, 2, 2, 4)
        self.labels_notes.set_mnemonic_widget(self.entries_notes)
        self.entries_notes.set_accepts_tab(False)
        
        self.entries_notes_textbuffer.connect('changed', lambda w: self.labels_notesremaining.set_text(str(255 - self.entries_notes_textbuffer.get_char_count()) + ' chars. left'))
        
        self.labels_tags = gtk.Label('_Tags:')
        self.labels_tags.set_use_underline(True)
        self.labels_tags.set_alignment(1.0, 0.5)
        self.uppertable.attach(self.labels_tags, 0, 1, 4, 5, gtk.FILL, xpadding=6)
        self.entries_tags = gtk.Entry()
        self.uppertable.attach(self.entries_tags, 1, 2, 4, 5)
        self.labels_tags.set_mnemonic_widget(self.entries_tags)
        
        user1 = dieu.settings.get_default_user().split(':')[0]
        user2 = dieu.settings.get_default_user().split(':')[1]
        globals()['self.database_'+dieu.settings.get_default_user()] = dieu.database.DieuDatabase(user1, user2)
    
        self.entries_tags_completion = gtk.EntryCompletion()
        globals()['self.liststore_'+dieu.settings.get_default_user()] = gtk.ListStore(str)
        globals()['self.liststore_'+dieu.settings.get_default_user()+'_list'] = []
        for tag in globals()['self.database_'+dieu.settings.get_default_user()].get_all_tags('Default'):
            if tag[1].lower() in globals()['self.liststore_'+dieu.settings.get_default_user()+'_list']:
                pass
            else:
                globals()['self.liststore_'+dieu.settings.get_default_user()].append([tag[1].lower()])
                globals()['self.liststore_'+dieu.settings.get_default_user()+'_list'].append(tag[1].lower())
        self.entries_tags_completion.set_match_func(self.match_func, None)
        self.entries_tags_completion.set_model(globals()['self.liststore_'+dieu.settings.get_default_user()])
        self.entries_tags_completion.set_text_column(0)
        self.entries_tags.set_completion(self.entries_tags_completion)
        self.entries_tags_completion.connect('match-selected', self.on_completion_match)
    
        
        self.entries_url.set_text(URL)
        self.entries_desc.set_text(Title)
        self.entries_notes_textbuffer.set_text(Extra)
        self.entries_tags.set_text(Tags)
        
        self.labels_accounts = gtk.Label('_Accounts:')
        self.labels_accounts.set_alignment(1.0, 0.5)
        self.labels_accounts.set_use_underline(True)
        self.uppertable.attach(self.labels_accounts, 0, 1, 5, 6, gtk.FILL, xpadding=6)
        self.combobox_accounts_liststore = gtk.ListStore(gobject.TYPE_STRING)
        self.combobox_accounts = gtk.ComboBox(self.combobox_accounts_liststore)
        self.combobox_accounts_cell = gtk.CellRendererText()
        self.combobox_accounts.pack_start(self.combobox_accounts_cell, True)
        self.combobox_accounts.add_attribute(self.combobox_accounts_cell, 'text', 0)
        self.uppertable.attach(self.combobox_accounts, 1, 2, 5, 6)
        self.combobox_accounts.append_text(dieu.settings.get_default_user())
        self.combobox_accounts.set_active(0)
        self.labels_accounts.set_mnemonic_widget(self.combobox_accounts)
        
        for account in dieu.settings.get_users():
            if account != dieu.settings.get_default_user():
                self.combobox_accounts.append_text(account)
        
        self.checkbox_private = gtk.CheckButton(label="_Make post private?", use_underline=False)
        self.checkbox_private.set_use_underline(True)
        self.uppertable.attach(self.checkbox_private, 1, 2, 6, 7)
        
        self.buttonhbox = gtk.HButtonBox()
        self.buttonhbox.set_layout(gtk.BUTTONBOX_DEFAULT_STYLE)
        self.buttonhbox.set_spacing(6)
        self.vbox.add(self.buttonhbox)
        
        self.buttons_help = gtk.Button(stock=gtk.STOCK_CANCEL)
        self.buttons_help_alignment = self.buttons_help.get_children()[0]
        self.buttons_help_hbox = self.buttons_help_alignment.get_children()[0]
        self.buttons_help_image, self.buttons_help_label = self.buttons_help_hbox.get_children()
        self.buttons_help_image.set_from_icon_name('help', gtk.ICON_SIZE_BUTTON)
        self.buttons_help_label.set_text('Help')
        self.buttons_help.connect('clicked', lambda w: webbrowser.open('http://code.google.com/p/dieu'))
        self.buttonhbox.add(self.buttons_help)
        
        self.buttons_reset = gtk.Button(stock=gtk.STOCK_CANCEL)
        self.buttons_reset_alignment = self.buttons_reset.get_children()[0]
        self.buttons_reset_hbox = self.buttons_reset_alignment.get_children()[0]
        self.buttons_reset_image, self.buttons_reset_label = self.buttons_reset_hbox.get_children()
        self.buttons_reset_image.set_from_icon_name('edit-clear', gtk.ICON_SIZE_BUTTON)
        self.buttons_reset_label.set_text('Reset')
        self.buttons_reset.connect('clicked', self.reset_fields)
        self.buttonhbox.add(self.buttons_reset)
        
        self.buttons_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
        self.buttons_cancel.connect('clicked', lambda w: self.cancel_action())
        self.buttonhbox.add(self.buttons_cancel)
        
        self.buttons_post = gtk.Button(stock=gtk.STOCK_ADD)
        self.buttons_post_alignment = self.buttons_post.get_children()[0]
        self.buttons_post_hbox = self.buttons_post_alignment.get_children()[0]
        self.buttons_post_image, self.buttons_post_label = self.buttons_post_hbox.get_children()
        self.buttons_post_label.set_text('Post')
        self.buttons_post.connect('clicked', self.add_post)
        self.buttonhbox.add(self.buttons_post)
        
        self.progressbars_post = gtk.ProgressBar()
        self.vbox.pack_start(self.progressbars_post)
        
        self.checkbox_private.show()
        self.buttons_post.show()
        self.buttons_cancel.show()
        self.buttons_reset.show()
        self.buttons_help.show()
        self.buttonhbox.show()
        self.combobox_accounts.show()
        self.labels_accounts.show()
        self.entries_tags.show()
        self.labels_tags.show()    
        self.entries_notes.show()
        self.scrolledwindow.show()
        self.labels_notesremaining.show()
        self.labels_notes.show()        
        self.entries_desc.show()
        self.labels_desc.show()
        self.entries_url.show()
        self.labels_url.show()
        self.uppertable.show()
        self.vbox.show()
        self.post_window.show()
    
    def reset_fields(self, foo):
        self.entries_url.set_text('')
        self.entries_desc.set_text('')
        self.entries_notes_textbuffer.set_text('')
        self.entries_tags.set_text('')
    
    def match_func(self, entries_tags_completion, key_string, iter, data):
        self.model = self.entries_tags_completion.get_model()
        self.modelstr = self.model[iter][0]
        if " " in key_string:
            last_word = key_string.split()[-1]
            return self.modelstr.startswith(last_word)
        return self.modelstr.startswith(key_string)
        
    def on_completion_match(self, entries_tags_completion, model, iter):
        current_text = self.entries_tags.get_text()
        if " " in current_text:
            current_text = " ".join(current_text.split()[:-1])
            current_text = "%s %s" % (current_text, model[iter][0])
        else:
            current_text = model[iter][0]

        self.entries_tags.set_text(current_text + ' ')
        self.entries_tags.set_position(-1)
        
        return True
    
    @dieu.util.threaded
    def add_post(self, elf):
        gtk.gdk.threads_enter()
        self.uppertable.set_sensitive(False)
        self.buttonhbox.set_sensitive(False)
        self.post_window.destroy()
        gtk.gdk.threads_leave()
        
        self.selected_user = self.combobox_accounts.get_active_text()
        
        self.user_name = self.selected_user.split(':')[0]
        self.user_system = self.selected_user.split(':')[1]
        self.user_password = dieu.settings.get_password(self.user_name, self.user_system)
        
        self.web_bookmarks = dieu.bookmark.DieuWebBookmarks(self.user_name, self.user_password, self.user_system)
        
        self.quick_db = dieu.database.DieuDatabase(self.user_name, self.user_system)
        
        if self.checkbox_private.get_active() == True:
            shared = 'no'
        else:
            shared = 'yes'
        self.add_post_posts_database = dieu.database.DieuDatabase(self.user_name, self.user_system)
        self.post_urls = []
        for post in self.add_post_posts_database.get_all_posts('Default'):
            self.post_urls.append(post[2])
        
        if self.entries_url.get_text() in self.post_urls:
            gtk.gdk.threads_enter()
            self.already_used_error_window = gtk.Window()
            self.already_used_error_window.set_border_width(12)
            self.already_used_error_window_table = gtk.Table(2, 1)
            self.already_used_error_window.add(self.already_used_error_window_table)
            self.already_used_error_window_image = gtk.Image()
            self.already_used_error_window_image.set_from_icon_name('@prefix@/share/pixmaps/dieu/dieu.svg', gtk.ICON_SIZE_DIALOG)
            self.already_used_error_window_table.attach(self.already_used_error_window_image, 0, 1, 0, 1)
            
            self.already_used_error_window_image.show()
            self.already_used_error_window_table.show()
            #self.already_used_error_window.show()
            gtk.gdk.threads_leave()
        
            if dieu.settings.get_libnotify() == True:
                n = pynotify.Notification('Bookmark already posted', '"<b>' + self.entries_desc.get_text() + '</b>"' + 'has already been posted, and was not bookmarked.', 'web-browser')
                n.set_urgency(pynotify.URGENCY_CRITICAL)
                n.set_timeout(pynotify.EXPIRES_NEVER)
                n.add_action("help", "Help", self.help_cb)
                n.add_action("ignore", "Ignore", self.ignore_cb)
                n.show()
        else:
            tags = self.entries_tags.get_text()
            for tag in tags:
                tag = tag.lower()
        
            self.web_bookmarks.add_post(self.entries_desc.get_text(), self.entries_notes_textbuffer.get_text(self.entries_notes_textbuffer.get_start_iter(), self.entries_notes_textbuffer.get_end_iter()), tags, self.entries_url.get_text(), shared)
            
            self.quick_db.add_post(self.entries_desc.get_text(), self.entries_url.get_text(), tags, self.entries_notes_textbuffer.get_text(self.entries_notes_textbuffer.get_start_iter(), self.entries_notes_textbuffer.get_end_iter()))
            
            self.dbtags = self.quick_db.get_all_tags('Default')
            self.dbtl = []
            for tag in self.dbtags:
                self.dbtl.append(tag[1])
            
            for tag in self.entries_tags.get_text().split(' '):
                if tag in self.dbtl:
                    pass
                else:
                    self.quick_db.add_tag(tag)
        
            if dieu.settings.get_libnotify() == True:
                self.positive_notification = pynotify.Notification('Bookmark posted', '"<b>' + self.entries_desc.get_text() + '</b>"' + ' bookmarked.', 'web-browser')
                self.positive_notification.set_urgency(pynotify.URGENCY_LOW)
                self.positive_notification.show()
        
        self.post_window.destroy()

    def ignore_action(notification, action):
        assert action == 'Post anyway'
        
        print 'something'
        
        #self.web_bookmarks.add_post(self.entries_desc.get_text(), self.entries_notes_textbuffer.get_text(self.entries_notes_textbuffer.get_start_iter(), self.entries_notes_textbuffer.get_end_iter()), self.entries_tags.get_text(), self.entries_url.get_text(), shared)
            
        positive_notification = pynotify.Notification('Bookmark posted', '"<b>' + self.entries_desc.get_text() + '</b>"' + ' bookmarked.', '@prefix@/share/pixmaps/dieu/dieu.svg')
        positive_notification.set_urgency(pynotify.URGENCY_LOW)
        positive_notification.show()
        
        notification.close()
    
    def cancel_action(notification, action):
        assert action == 'Cancel'
        
        notification.close()

    def cancel_action(self):
        self.post_window.destroy()
        del self
